package com.kingzoon.seckill.base.shiro;

import java.util.HashMap;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ch.qos.logback.classic.Logger;

import com.kingzoon.seckill.dto.Result;
import com.kingzoon.seckill.enums.MacroDefine;
import com.kingzoon.seckill.service.MemberLoginService;
import com.kingzoon.seckill.util.UtilTools;
import com.kingzoon.seckill.util.WebUtil;

/**
 * 权限检查类
 * @author raymond
 *
 */
public class Realm extends AuthorizingRealm {
	
	private Logger log = (Logger) LoggerFactory.getLogger(Realm.class);
	
	@Autowired
	private MemberLoginService memberLoginService;

	//权限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	//登录验证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authToken;
        StringBuilder sb = new StringBuilder(100);
        for (int i = 0; i < token.getPassword().length; i++) {
            sb.append(token.getPassword()[i]);
        }
		Result<HashMap<String,Object>> rs = new Result<HashMap<String,Object>>(false, MacroDefine.JC_CODE.R_9999.getCode(), MacroDefine.JC_CODE.R_9999.getMessage());
		HashMap<String,Object> mapParam = new HashMap<String, Object>();
		mapParam.put("phoneNo", token.getUsername());
		mapParam.put("password", sb.toString());
		memberLoginService.doBusiness(mapParam, rs);
		if(rs.isSuccessful()){
            WebUtil.saveCurrentUser(rs.getData().get("memberId"));
            saveSession((String)rs.getData().get("loginName"));
			AuthenticationInfo authInfo = new SimpleAuthenticationInfo(rs.getData().get("loginName"), rs.getData().get("password"), UtilTools.valueOf(rs.getData().get("memberId")));
			return authInfo;
		}
		return null;
	}
	
    /** 保存session */
    private void saveSession(String account) {
        // 踢出用户
        //sysSessionService.deleteByAccount(account);
        //SysSession record = new SysSession();
        //record.setAccount(account);
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        //record.setSessionId(session.getId().toString());
        String host = (String)session.getAttribute("HOST");
        //record.setIp(StringUtils.isBlank(host) ? session.getHost() : host);
        //record.setStartTime(session.getStartTimestamp());
        //sysSessionService.update(record);
        log.debug("更新会话状态session=" + session.getId());
    }

}
